#include "client.h"
#include "QtDebug"
#include <QtGui/QLabel>

/*

*Main client constructor*

@param addressParam -> Client IP Address
@param portParam -> CLient Port
@param nameParam -> Client Username

**/

Client::Client(QString addressParam, quint16 portParam, QString nameParam){

    // Create a new QTcp Client
    client = new QTcpSocket(this);

    address = addressParam;
    port = portParam;
    userName = nameParam;

    //Once a connection is established, send the username to the server
    connect(client, SIGNAL(connected()),this, SLOT(sendUserInformation()));
}

/*

*bool startClient method*

Description:
Get the user IP and Port information and try to establish a connection.
Return a success or failure message depending on connection.

**/

bool Client::startClient(){

    // Get user IP Address
    QHostAddress addr(address);

    // Connect the client to the server
    client->connectToHost(addr, port);

    // Check for client timeout
    if(client->waitForConnected(5000))
    {
	qDebug() << "Successfully Connected To Host as :" << userName<< endl;
	return true;
    }
    else
    {
	qDebug() << "Error connecting to server :" << endl;
	return false;
    }
}

/*

*recieveMessage method*

Description:
Create an int to store the bytes receieved from the server/client.
Check the size of the bytes to determine is message was receieved

**/

void Client::receiveMessage()
{
    // Get the bytes sent from the TCP Socket
    int bytes = client->bytesAvailable();

    // Check for byte size from socket
    if(bytes > 0)
    {
	char buffer[bytes+1];
	client->read(buffer, bytes);
	qDebug() << "Server: " << buffer << endl << flush;
    }
}

/*

*sendUserInformation method*

**/

void Client::sendUserInformation()
{
    QByteArray datablock;
    QDataStream sendStream(&datablock,QIODevice::WriteOnly);
    sendStream.setVersion(QDataStream::Qt_4_0);

    // [0] tells the server we're sending a username
    sendStream << quint16(0)<< userName;

    // Send the datablock username out
    client->write(datablock);

}

/*

*sendMessage method*

**/

void Client::sendMessage()
{

    QByteArray datablock;
    QDataStream sendStream(&datablock,QIODevice::WriteOnly);
    sendStream.setVersion(QDataStream::Qt_4_0);

    // Set a char buffer for the message
    char buffer [1024];

    // Read in the message from the user
    cin.getline(buffer, 1024);
    QString message(buffer);

    // [1] tells the server we're sending a message
    sendStream <<quint16(1)<<message;

    // Send the message block out
    client->write(datablock);

}

